<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\model\RoleModel;
use app\admin\model\UserModel;
use app\admin\model\AreaModel;
use app\admin\model\CompanyModel;
use think\Db;
use think\Exception;
use org\BaiduMap;

class Company extends Base
{
    //用户列表
    public function index()
    {
        if(request()->isAjax()){

            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;

            $where = [];
            if (!empty($param['searchText'])) {
                // $where['user_name'] = ['like', '%' . $param['searchText'] . '%'];
            }

            $id = session('id');
            $user = new UserModel();
            $company = new CompanyModel();
            $user_type = $company->getUserType($id);
            // $userInfo = $user->getOneUser($id);
            // $user_type = false;
            // if($userInfo){
            //     $user_type = $user::hasWhere('company',['mobile'=>$userInfo['user_name']])->find();
            //     echo $user::getLastSql();
            //     exit;
            // }


            // $user_type = $company->getCompanyInfo($id);
            if(session('role_id') == 3){
                $where['a.role'] = session('role_id');
                $where['a.top_cid'] = $user_type->aid;
            }else{
                $where['a.role'] = ['gt',0];
                $where['a.top_cid'] = ['gt',0];
            }
            $selectResult = $company->getCompanyByWhere($where, $offset, $limit);

            $status = config('user_status');
            $level = config('company_level');
            // 拼装参数
            foreach($selectResult as $key => $vo){
                // $selectResult[$key]['last_login_time'] = date('Y-m-d H:i:s', $vo['last_login_time']);
                $selectResult[$key]['showstatus'] = $status[$vo['status']];
                $selectResult[$key]['showlevel'] = $level[$vo['level']];

                // if( 1 == $vo['id'] ){
                //     $selectResult[$key]['operate'] = '';
                //     continue;
                // }
                $selectResult[$key]['operate'] = showOperate($this->makeButton($vo['id'],$vo['status']));
            }

            $return['total'] = $company->getAllCompany($where);  //总数据
            $return['rows'] = $selectResult;

            return json($return);
        }

        return $this->fetch();
    }

    // 添加用户
    public function userAdd()
    {
        if(request()->isPost()){

            $param = input('post.');
            $company = new CompanyModel();
            $param['provinceName'] = db::name('areas')->where('area_id',$param['province'])->value('area_name');
            $param['cityName'] = db::name('areas')->where('area_id',$param['city'])->value('area_name');
            $param['distName'] = db::name('areas')->where('area_id',$param['dist'])->value('area_name');
            $$param['address'] = $param['address'];
            $add_name = $param['provinceName'].$param['cityName'].$param['distName'].$param['address'];
            $baidu = new BaiduMap();
            $coordinate = $baidu::getCoordinateByName($add_name);
            if(is_array($coordinate)){
                if($coordinate['result']['location']['lng']){
                    $lng = $coordinate['result']['location']['lng'];
                    $param['lng'] = $lng;
                }
                if($coordinate['result']['location']['lat']){
                    $lat = $coordinate['result']['location']['lat'];
                    $param['lat'] = $lat;
                }
            }
            if($lng && $lat){
                $citycode = $baidu::getCodeByPoint($lng, $lat);
                $companyInfo = $company->getTopCompanyInfo($param['top_cid']);
                if($param['role_id'] == 3){
                    if($companyInfo['level']+1 == 1){
                        $param['code'] = $citycode['citycode'];
                    }elseif($companyInfo['level']+1 == 2){
                        $param['code'] = $citycode['citycode'];
                    }elseif($companyInfo['level']+1 == 3){
                        $param['code'] = $citycode['adcode'];
                    }
                    $param['level'] = $companyInfo['level']+1;
                }else{
                    $param['code'] = $citycode['adcode'];
                }
            }
                $param['role'] = $param['role_id'];
                $user = new UserModel();
                $result = $this->validate($param,'CompanyValidate.addData');
                    if(true !== $result){
                        // 验证失败 输出错误信息
                        return msg('-1', url('company/index'), $result);
                    }
                Db::startTrans();
                try{
                        $company->save($param);
                        $user->password = md5($param['password']);
                        $user->role_id = $param['role_id'];
                        $user->real_name = $param['name'];
                        $user->user_name = $param['mobile'];
                        $user->status = 1;
                        $addUser = $company->user()->save($user);
                    
                    // 提交事务
                    if($addUser){
                        Db::commit();
                        return msg(1, url('company/index'), '添加用户成功');
                    }else{
                        throw new \think\Exception("Error");
                    }
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    return msg('-1', '', $e->getMessage());
                }
        }

        $user_id = session('id');
        $role_id = session('role_id');
        $role = new RoleModel();
        $AreaModel = new AreaModel();
        $CompanyModel = new CompanyModel();
        $this->assign([
            'role' => $role->getPartRole(),
            'status' => config('user_status'),
            'area' => $AreaModel->getAreaName(),
            'company' => $CompanyModel->getTopCompany($user_id,$role_id),
        ]);

        return $this->fetch();
    }

    // 编辑用户
    public function userEdit()
    {
        $company = new CompanyModel();
        // if(request()->isPost()){

            $param = input('param.');
            $flag = $company->editUser($param);

            return json(msg($flag['code'], $flag['data'], $flag['msg']));
        // }

        // $id = input('param.id');
        // $role = new RoleModel();
        // $this->assign([
        //     'user' => $company->getOneUser($id),
        //     'status' => config('user_status'),
        //     // 'role' => $role->getRole()
        // ]);
        // $this->assign([
        //     'user' => $company->getOneUser($id),
        //     'status' => config('user_status'),
        //     'role' => $role->getRole()
        // ]);
        // return $this->fetch();
    }

    // 删除用户
    // public function userDel()
    // {
    //     $id = input('param.id');

    //     $company = new CompanyModel();
    //     $flag = $company->delUser($id);
    //     return json(msg($flag['code'], $flag['data'], $flag['msg']));
    // }

    /**
     * 拼装操作按钮
     * @param $id
     * @return array
     */
    private function makeButton($id,$status)
    {
        if($status == 1){
            return [
                '禁用' => [
                    'auth' => 'company/useredit',
                    // 'href' => url('company/userEdit', ['id' => $id]),
                    'href' => "javascript:userEdit(" .$id .','.$status.")",
                    'btnStyle' => 'primary',
                    'icon' => 'fa fa-paste'
                ],
                // '删除' => [
                //     'auth' => 'user/userdel',
                //     'href' => "javascript:userDel(" .$id .")",
                //     'btnStyle' => 'danger',
                //     'icon' => 'fa fa-trash-o'
                // ]
            ];
        }else{
            return [
                '启用' => [
                    'auth' => 'company/useredit',
                    // 'href' => url('company/userEdit', ['id' => $id]),
                    'href' => "javascript:userEdit(" .$id .','.$status.")",
                    'btnStyle' => 'primary',
                    'icon' => 'fa fa-paste'
                ],
                // '删除' => [
                //     'auth' => 'user/userdel',
                //     'href' => "javascript:userDel(" .$id .")",
                //     'btnStyle' => 'danger',
                //     'icon' => 'fa fa-trash-o'
                // ]
            ];
        }
    }
}
